﻿using System.Collections;
using System.Collections.Generic;

//事件派发类
public class Dispatcher {
	private Dictionary<object,List<OneDelegate>> eventMap = new Dictionary<object, List<OneDelegate>>();
	private static Dispatcher _instance;
	public static Dispatcher Instance{
		get{
			if(_instance == null){
				_instance = new Dispatcher();
			}
			return _instance;
		}
	}

	private Dispatcher(){

	}
	//事件监听
	public void AddEventListener(object key,OneDelegate cb,int index = -1)
	{
		List<OneDelegate> cbList = eventMap.GetValue(key,new List<OneDelegate>());
		cbList.Remove(cb);//防止一个函数被多次添加
		if(index < 0) cbList.Add(cb);
		else cbList.Insert(index,cb);
		eventMap.AddOrReplace(key, cbList);
	}
	//事件派发
	public void DispatchEvent(object key,object param = null)
	{
		List<OneDelegate> cbList = eventMap.GetValue(key,new List<OneDelegate>());
		foreach(OneDelegate cb in cbList){
			cb(param);
		}
	}
	//移除制定下标函数监听
    public void RemoveEventListener(object key,int index = -1){
		if(index == -1) eventMap.RemoveValue(key);
		else{
			List<OneDelegate> cbList = eventMap.GetValue(key,new List<OneDelegate>());
			cbList.RemoveAt(index);
			eventMap.AddOrReplace(key,cbList);
		}
	}
	//移除制定函数监听
    public void RemoveEventListener(object key,OneDelegate cb){
		List<OneDelegate> cbList = eventMap.GetValue(key,new List<OneDelegate>());
		cbList.Remove(cb);//防止一个函数被多次添加
	}
	//移除所有事件监听
	public void RemoveAllEventListener(){
		//不确定自己会不会清空
		// foreach (var item in eventMap)
		// {
		// 	item.Value.Clear();
		// }
		eventMap.Clear();
	}
}
